<?php
namespace Modules\Book\Library;

use Modules\Region\Entity\Block as BlockEntity;
use Phalcon\Di;
use MongoDB\BSON\ObjectID;
use Modules\Book\Models\NodeBook;

class Block
{

    public static function bookToc(BlockEntity $blockEntity)
    {
        if (isNode()) {
            return self::_bookToc($blockEntity);
        } else {
            return self::_bookList($blockEntity);
        }
    }

    protected static function _bookToc(BlockEntity $blockEntity)
    {
        $node = getNode();
        if (!$node || !isset($node->book_id) || !$node->book_id) {
            return false;
        }
        $di = Di::getDefault();
        $data = NodeBook::findFirst([
            'conditions' => [
                'bid' => $node->book_id,
            ]
        ]);
        $bookNode = $di->getShared('entityManager')->get('node', [
            'conditions' => [
                '_id' => new ObjectID($node->book_id)
            ]
        ]);
        if (!$data || !$bookNode) {
            return false;
        }
        $nodeId = strval($node->getId());
        $output = array(
            '#templates' => array(
                'block-bookToc',
                'block-bookToc-' . $node->contentModel,
                'block-bookToc-' . $node->book_id,
                'block-bookToc-' . $node->book_id . '-' . $nodeId,
            ),
            '#module' => 'book',
            'currentId' => $nodeId,
            'bookNode' => $bookNode,
            'data' => $blockEntity,
            'bookToc' => $data,
            'currentNode' => $node
        );
        return $output;
    }

    protected static function _bookList(BlockEntity $blockEntity)
    {
        $di = Di::getDefault();
        $data = $di->getShared('entityManager')->get('node', [
            'conditions' => [
                'contentModel' => 'book'
            ],
            'sort' => [
                'changed' => -1,
            ],
            'limit' => isset($blockEntity->limit) ? intval($blockEntity->limit) : 7,
            'skip' => 0,
        ]);
        return  array(
            '#templates' => array(
                'block-bookList',
            ),
            'data' => $blockEntity,
            'bookList' => $data,
        );
    }
}